package com.example;

import org.apache.pulsar.client.api.*;

import java.util.UUID;

/**
 * 简单的消息生产者
 *
 * @author linfeng
 * @date 2022/2/25 10:33
 */
public class TestProducer {

    public static final String TOPIC_NAME = "6064B571445A4B349EC23D133AEA0650";


    public static PulsarClient getPulsarClient() throws PulsarClientException {
        PulsarClient pulsarClient = PulsarClient
                .builder()
                .serviceUrl("pulsar://localhost:6650")
                .build();
        return pulsarClient;
    }

    public static Producer<String> getProducer(PulsarClient pulsarClient) throws PulsarClientException {
        ProducerBuilder<String> producerBuilder = pulsarClient
                .newProducer(Schema.STRING)
                .accessMode(ProducerAccessMode.Exclusive)
                .topic(TOPIC_NAME);

        Producer<String> producer = producerBuilder.create();
        return producer;
    }

    public static void main(String[] args) throws PulsarClientException {

        try (PulsarClient pulsarClient = getPulsarClient();
        Producer<String> producer = getProducer(pulsarClient)){

            String message = UUID.randomUUID().toString();
            // MessageId messageId = producer.send(message);
            MessageId messageId = producer.newMessage().key("--key2").value(message).send();

            System.out.println("消息发送成功，messageId: " + messageId + ", 消息内容：" + message);
        }
    }
}
